package com.ryder.petmatediarybackend.common.config.web;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.ryder.petmatediarybackend.common.exception.BusinessException;
import com.ryder.petmatediarybackend.common.interceptor.AccessLogInterceptor;
import com.ryder.petmatediarybackend.module.auth.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 描述: MVC 全局配置（CORS、Jackson、Sa-Token 拦截器）
 *
 * @author Ryder
 * @version 1.1
 * @since 1.0
 * 更新日期: 2025/10/25
 */
@Configuration
@RequiredArgsConstructor
public class GlobalConfig implements WebMvcConfigurer {

    private static final Logger log = LoggerFactory.getLogger(GlobalConfig.class);

    @Value("${cors.allowed-origins:*}")
    private String[] allowedOrigins;

    private final ObjectMapper objectMapper;
    private final AccessLogInterceptor accessLogInterceptor;
    private final TokenService tokenService;

    /**
     * CORS 配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns(allowedOrigins)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
        log.info("CORS 已配置: allowedOrigins={}", (Object) allowedOrigins);
    }

    /**
     * 自定义 Jackson 消息转换器，处理空值
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(mappingJackson2HttpMessageConverter());
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        ObjectMapper copy = objectMapper.copy(); // 避免修改原 Bean
        copy.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        copy.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return new MappingJackson2HttpMessageConverter(copy);
    }

    /**
     * 注册全局拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 1. 访问日志拦截器（最先执行，记录所有请求）
        registry.addInterceptor(accessLogInterceptor)
                .addPathPatterns("/**")
                .order(1);
        log.info("访问日志拦截器已注册");

        // 2. Sa-Token 认证拦截器
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 打印请求路径和 Token 信息（调试用）
            String requestPath = SaHolder.getRequest().getRequestPath();
            String authHeader = SaHolder.getRequest().getHeader("Authorization");
            String tokenValue = StpUtil.getTokenValue();
            log.info("Sa-Token 拦截器 | 路径: {} | Authorization Header: {} | Token: {}", 
                    requestPath, authHeader, tokenValue);
            
            // 放行路径列表（不需要登录的接口）
            SaRouter.notMatch(
                    "/auth/register",        // 注册接口
                    "/auth/login",           // 登录接口
                    "/auth/refresh",         // 刷新 Token 接口
                    "/test/**",              // 测试接口
                    "/doc.html",             // Knife4j 文档页面
                    "/swagger-ui.html",      // Swagger UI 页面
                    "/swagger-ui/**",        // Swagger UI 资源
                    "/v3/api-docs/**",       // OpenAPI 3 文档
                    "/swagger-resources/**", // Swagger 资源
                    "/webjars/**",           // Webjars 静态资源
                    "/favicon.ico"           // 网站图标
            ).match("/**")                   // 拦截所有其他路径（包括 /admin/** 和 /auth/logout）
            .check(r -> {
                log.info("Sa-Token 检查登录 | 路径: {}", requestPath);
                
                // 1. 检查登录状态
                StpUtil.checkLogin();
                
                // 2. 检查 Token 是否在黑名单
                String token = StpUtil.getTokenValue();
                if (token != null && tokenService.isInBlacklist(token)) {
                    log.warn("Token 在黑名单中，拒绝访问：token={}", token);
                    throw new BusinessException("令牌已失效，请重新登录");
                }
            });
        })).addPathPatterns("/**")
           .order(2);
        
        log.info("Sa-Token 拦截器已注册，放行路径: /auth/register, /auth/login, /auth/refresh, /test/**, /doc.html, /v3/api-docs/**");
    }
}